<template>
  <div>
    <!-- 文章列表 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
        offset="50"
      >
        <!-- 文章列表 -->
        <ArticleItem
          v-for="(item,index) in articlesList"
          :key="item.art_id+index"
          :obj="item"
          @click.native="$router.push(`/article_detail?aid=${item.art_id}`)"
        >
        </ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { timeAgo } from '@/utils/day.js'
import ArticleItem from './components/ArticleItem.vue'
import { articlesListAPI } from '@/api'
export default {
  props: {
    cid: Number
  },
  data () {
    return {
      articlesList: [],
      finished: false,
      loading: false,
      nextTime: null,
      isLoading: false
    }
  },
  methods: {
    timeAgo: timeAgo,
    onLoad () {
      if (this.articlesList.length > 0) {
        this.getarticlesList()
      }
    },
    async getarticlesList () {
      const res = await articlesListAPI(this.cid, this.nextTime)

      res.data.data.results.forEach((item) => {
        item.pubdate = this.timeAgo(item.pubdate)
      })
      // this.articlesList = res.data.data.results
      // 如果无数据
      if (res.data.data.results.length === 0) {
        this.finished = true // 告诉list组件直接底部显示没有更多数据
      } else {
        this.nextTime = res.data.data.pre_timestamp // 保存下一页数据的时间(做分页用)
        this.articlesList = [...this.articlesList, ...res.data.data.results]
        // 等待网络请求结果后
        this.loading = false // 底部加载更多状态
      }
    },
    onRefresh () {
      this.nextTime = null
      this.getarticlesList()
      this.isLoading = false
    }
  },
  components: {
    ArticleItem
  },
  async created () {
    // const res = await articlesListAPI(this.cid)
    // // console.log(res)
    // res.data.data.results.forEach((item) => {
    //   item.pubdate = this.timeAgo(item.pubdate)
    // })
    // this.articlesList = res.data.data.results
    this.getarticlesList()
  }
}
</script>
